<template>
  <div>
    <div class="title" style="margin-bottom: 5px;">
      <span>{{ props.label + ' 预览' }}</span>
    </div>
    <div class="img-layout">
      <el-tooltip
        class="box-item"
        effect="dark"
        content="点击更换图片."
      >
        <div class="ant-image" @click.stop="showImageLib">
          <img class="imgS" :src="icon_url" @error="onImgError"  />
        </div>
      </el-tooltip>
    </div>

	<ElFormItem :label="props.label">
		<ElInput v-model="input_model" :placeholder="'请输入'+props.label" style="width: 100%;"/>
	</ElFormItem>
	
    <!-- 替换 el-dialog 弹窗为自定义弹窗 -->
	<!-- 使用 Transition 包裹，并指定 Animate.css 的类名 -->
	<Transition
		enter-active-class="animate__animated animate__slideInRight"
		leave-active-class="animate__animated animate__slideOutRight"
  	>
		<div class="imgage-material-lib"   v-show="openIconLibrary">
			<div class="panel-head">
				<div class="title">
					<span>图片素材库</span>
				</div>
				<div class="panel-head-icon" @click.stop="handleCloseClick">
					<i class="iconfont-sys">&#xe7dc;</i>
				</div>
			</div>

			<div class="panel-search">
				<div  class="panel-search-select">
					<el-tree-select clearable popper-class="catalogTree" v-model="classifyId" :data="options" :props="defaultProps" :check-strictly="true" :render-after-expand="false" @change="handleChange" />
				</div>
				<div class="panel-search-input">
					<el-input
						v-model="keywords"
						placeholder="请输入关键字"
						class="input-with-select"
						:suffix-icon="Search"
						@keydown="handleSearch"
						style="margin-left: 4px;"
					>
					</el-input>
				</div>
			</div>
			<div class="panel-list">
				<div
					class="img-box"
					v-for="(img, idx) in tableData"
					:key="img.id"
					@click.stop="handleSelectedImg(img)"
					style="flex-direction: column; align-items: center; justify-content: flex-start;"
				>
					<el-tooltip
						effect="dark"
						placement="top"
						:show-after="100"
						:hide-after="0"
						:offset="10"
						popper-class="img-preview-tooltip"
					>
						<template #content>
							<img
								:src="getImageSrc(img.url)"
								:alt="img.name || ''"
								class="img-preview-large"
							/>
						</template>
						<template #default>
							<img
								:src="getImageSrc(img.url)"
								:alt="img.name || ''"
								class="img-preview-thumb"
							/>
						</template>
					</el-tooltip>
					<div class="img-name">{{ img.name || '未命名' }}</div>
				</div>
			</div>
			
			<div style="padding: 5px;display: flex;    display: flex;justify-content: center;align-items: center;">
				<el-pagination
					v-model:current-page="_cur"
					v-model:page-size="_pageSize"
					:page-sizes="[100, 200, 300, 400]"
					:pager-count="5"
					background
					size="small"
					layout="sizes, prev, pager, next"
					:total="_totalPage"
					@size-change="handleSizeChange"
					@current-change="currentChange"
				/>
			</div>
		</div>
	</Transition>
  </div>
</template>


<script lang="ts" setup>
	import { MaterialService } from '@/api/visual/materialApi'
	import {
	  Search
	} from '@element-plus/icons-vue'
	import notFoundImg from '@/assets/img/state/404.png'
	import 'animate.css';

	const props = defineProps({
		baseUrl: {
			type: String,
			default: () => ''
		},
		pidentifier: {
			type: String,
			default: () => ''
		},
		identifier: {
			type: String,
			default: () => {}
		},
		label: {
			type: String,
			default: () => {}
		},
		required: {
			type: Boolean,
			default: () => false
		},
		value: {
			type: String,
			default: () => {}
		},
	})
	
	const defaultProps = {
	  children: 'children',
	  label: 'name',
	  value:'id'
	}
	
	const loading=ref<boolean>(false);
	const keywords = ref('');
	const options = ref<any[]>();
	const classifyId=ref('');
	let tableData=ref<any[]>([])
	const baseUrl = ref<string>('');
	const _cur=ref(1);
	const _total=ref(0);
	const _totalPage=ref(0);
	const _pageSize=ref(20);
	
	
	const openIconLibrary=ref<boolean>(false);
	const error=ref(false);
	const error_message=ref();
	const input_model=ref();
	const emits = defineEmits(['onchange'])
	const icon_url=ref();
	watch(props, () => {
	  baseUrl.value = props.baseUrl;
	  input_model.value = props.value;
	  const val = input_model.value;
	  if (!val) {
	    icon_url.value = notFoundImg;
	  } else if (/^(https?:)?\/\//i.test(val)) {
	    icon_url.value = val;
	  } else {
	    icon_url.value = baseUrl.value + '/visual/material/image/' + val + '?' + new Date().getTime();
	  }
	}, { immediate: true, deep: true });


	function getImageSrc(url: any) {
		if (url) return `${baseUrl.value}/visual/material/image/${url}`
		return notFoundImg
	}

	
	const validate=()=>{
		if(props.required && input_model.value==''){
			error.value=true
			error_message.value=props.label+'必填.'
			return;
		}
		error.value=false
		error_message.value=''
	}
	
	// 替换 selectedIcon 逻辑为直接控制 openIconLibrary
	// 选择图片后自动关闭弹窗并回填
	const handleSelectedImg = (data: any) => {
	  input_model.value = data.url;
	  icon_url.value = getImageSrc(data.url);
	  validate();
	  emits('onchange', {
	    pidentifier: props.pidentifier,
	    identifier: props.identifier,
	    value: input_model.value,
	  });
	  openIconLibrary.value = false;
	};

	const handleSizeChange = (val: number) => {
		_pageSize.value=val
		load();
	}
	
	const handleCloseClick=()=>{
		openIconLibrary.value=!openIconLibrary.value
	}
	
	async function loadOptions() {
	  options.value = await MaterialService.getLoadAll({});
	}
	
	const currentChange=(cur:number)=>{
		_cur.value= cur
		load();
	}
	
	const handleChange=(id:any)=>{
		classifyId.value=id;
		load();
	}
	
	const handleSearch=(e:any)=>{
		if(e.keyCode == 13) {
			load();
		}
	}
	
	const load= async()=>{
		loading.value=true;
		try{
			const _data=await MaterialService.imagePages({
				categoryId:classifyId.value,
				keywords:keywords.value,
				cur:_cur.value,
				limit:_pageSize.value
			})
			_total.value=_data.totalRow
			_totalPage.value=_data.totalPage
			tableData.value= _data.list
		}finally{
			loading.value=false;
		}
	}
	
	onMounted(() => {
		input_model.value=props.value

	});

	function onImgError(e: Event) {
  (e.target as HTMLImageElement).src = notFoundImg
}

// 新增弹出图片库方法，点击主图标时加载图片库
const showImageLib = () => {
	openIconLibrary.value = true;
  	nextTick(() => {
		loadOptions();
		load();
  	});
}

</script>

<style scoped>

.imgS{
	object-fit: contain;
    height: 50px;
    background: #252f4a;
    padding-top: 10px;
    width: 300px;
	cursor: pointer;
}


:deep(.el-dialog__header){
	padding: 0px !important;
}

:deep(.el-dialog__body){
	padding: 0px !important;
}



.style-row{
	margin-top: 8px;
}

.style-row .item{
	border: 1px solid var(--art-card-border);
	width: 120px;
	height: 120px;
}
.style-row .item .img-pane{
	padding: 2px;
}

.style-row .item .img-pane .imgS{
	width: 120px;
	height: 120px;
	object-fit: contain;
}

.custom-modal-mask {
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.25);
  z-index: 3000;
  display: flex;
  align-items: center;
  justify-content: center;
}
.custom-modal-content {
  min-width: 340px;
  min-height: 320px;
  background: linear-gradient(135deg, #232a3a 60%, #1e90ff22 100%);
  border-radius: 22px;
  box-shadow: 0 8px 48px #1e90ff33, 0 2px 8px #fff1 inset;
  padding: 24px 24px 12px 24px;
  position: relative;
  animation: modalIn 0.18s;
}
@keyframes modalIn {
  from { transform: scale(0.95); opacity: 0.5; }
  to   { transform: scale(1); opacity: 1; }
}
.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 20px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 12px;
}
.close {
  font-size: 22px;
  cursor: pointer;
  color: #bfc6d1;
  transition: color 0.2s;
}
.close:hover {
  color: #409eff;
}

.imgage-material-lib{
    position: fixed;
    z-index: 99999999999; 
    top: 75px;
    right: 0px;
    width: 400px;
	height: calc(100vh - 78px);
	border: 1px solid var(--art-card-border);
	background-color: var(--art-main-bg-color);
	.panel-head{
		height: 53px;
		min-height: 53px;
		border-bottom: 1px solid var(--art-card-border);
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-left: 8px;
		padding-right: 8px;
	}

  .panel-head-icon{
    width: 35px;
    height: 35px;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    font-size: 16px;
  }
  .panel-head-icon:hover{
    color: red;
    box-shadow: 0 6px 24px #409eff55;
  }

  .panel-search{
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: flex-start;
    padding: 8px;
  }
  .panel-search-select{
    width: 190px;
  }
  .panel-search-input{
    width: 190px;
  }
  .panel-list{
    width: 390px;
    display: flex;
    grid-template-columns: repeat(2, 1fr);
    gap: 6px;
    padding: 0px 0px 0px 5px;
	height: calc(100% - 158px);
	border-bottom: 1px solid var(--art-card-border);
    .img-box {
      width: 168px;
      height: 90px;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      border-radius: 8px;
      position: relative;
      border: 1px solid var(--art-card-border);
      padding: 5px;
	  box-shadow: 0 4px 32px #1e90ff33, 0 1.5px 0.5px #fff1 inset;
    }
    .img-box img {
      width: 100%;
      height: 100%;
      object-fit: contain;
      border-radius: 18px 18px 0 0;
      transition: transform 0.4s cubic-bezier(.4,2,.6,1), opacity 0.4s;
      opacity: 0.92;
      cursor: pointer;
    }
  }  

}

.img-preview-large {
  width: 300px;
  height: auto;
  object-fit: contain;
  display: block;
  background: none;
}

.img-preview-thumb {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 18px 18px 0 0;
  transition: transform 0.4s cubic-bezier(.4,2,.6,1), opacity 0.4s;
  opacity: 0.92;
  cursor: pointer;
}

.img-name {
  width: 100%;
  text-align: center;
  font-size: 13px;
  color: #8a99b3;
  margin-top: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.6;
}

</style>